package top.fzqblog.music.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.List;

import top.fzqblog.music.event.PlayEvent;
import top.fzqblog.music.event.SongChangeEvent;
import top.fzqblog.music.model.Song;
import top.fzqblog.music.util.MusicPlayer;

import static top.fzqblog.utils.Constants.TAG;

/**
 * Created by 抽离 on 2017/10/23 0023.
 */

public class MediaService extends Service{

    @Override
    public void onCreate() {
        Log.i(TAG, "onCreate: ");
        super.onCreate();
        EventBus.getDefault().register(this);
    }

    List<Song> songList;

    @Subscribe
    public void onEvent(PlayEvent playEvent){
        switch (playEvent.getPlayAction()){
            case PLAY:
                songList = playEvent.getSongList();
                MusicPlayer.getPlayer().setQueue(songList, playEvent.getIndex());
                EventBus.getDefault().post(new SongChangeEvent(playEvent.getSong(), 4));
                break;
            case STOP:
                if(MusicPlayer.getPlayer().getCurrentPosition() != 0) {
                    MusicPlayer.getPlayer().pause();
                    EventBus.getDefault().post(new SongChangeEvent(1));//停止播放
                    break;
                }
            case RESUME:
                Log.i(TAG, "currentPosition: " + MusicPlayer.getPlayer().getCurrentPosition());
                if(MusicPlayer.getPlayer().getCurrentPosition() == 0){
                    Toast.makeText(this, "还没有选择歌曲！", Toast.LENGTH_SHORT).show();
                }else {
                    MusicPlayer.getPlayer().resume();
                    EventBus.getDefault().post(new SongChangeEvent(2));//播放状态
                }
                break;
            case  NEXT:
                MusicPlayer musicPlayer = MusicPlayer.getPlayer();
                if(musicPlayer.getmQueue() != null && musicPlayer.getmQueue().size() > 0){
                    musicPlayer.next();
                    int position = musicPlayer.getmQueueIndex();
//                Log.i(TAG, "position: "+position);
//                Log.i(TAG, "songList: " + songList);
                    EventBus.getDefault().post(new SongChangeEvent(songList.get(position), 3));
                }
                break;
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

}
